package com.jplus.core.mvc.response.defaults;

import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.mvc.response.ResponseHandle;
import com.jplus.core.mvc.vo.Model;
import com.jplus.core.mvc.vo.ModelAndView;
import com.jplus.core.mvc.vo.View;
import com.jplus.core.utill.JSON;
import com.jplus.core.utill.JUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认的JSP 处理器，可替换成其他
 * 
 * @author Yuanqy
 *
 */
public class JSPResponseHandle extends ResponseHandle {
	private final Logger log = LoggerFactory.getLogger(JSPResponseHandle.class);

	public JSPResponseHandle() {
		super.registerView(this);
	}

	@Override
	public void handle(String requestUri, Object body, HttpServletRequest req, HttpServletResponse res,
			ApplicationContext context) {
		try {
			String FRAMEWORK_VIEW_PREFIX = context.getEnvironment().getProp("frame.view.prefix", "/WEB-INF/jsp/");
			String FRAMEWORK_VIEW_SUFFIX = context.getEnvironment().getProp("frame.view.suffix", ".jsp");

			Model m = new Model();
			View v = new View();
			// ==1.解析返回对象=========
			if (body instanceof ModelAndView) {
				m = ((ModelAndView) body).getModel();
				v = ((ModelAndView) body).getView();
			}
			if (body instanceof Map) {
				m = JSON.parseBean(JSON.toJSONString(body), Model.class);
			}
			if (body instanceof View)
				v = (View) body;
			if (body instanceof Model)
				m = (Model) body;
			if (body instanceof String) {
				if (v == null)
					v = new View();
				v.setPath(body.toString());
			}
			// ==2.填充Attr=========
			if (m != null) {
				for (Entry<String, Object> e : m.entrySet()) {
					req.setAttribute(e.getKey(), e.getValue());
				}
			}
			// ==3,组装Path=========
			if (JUtil.isEmpty(v.getPath()))
				v.setPath(requestUri);
			if (v.getType() == null)
				v.setType(View.TYPE.FORWARD);
			String path = FRAMEWORK_VIEW_PREFIX.concat(v.getPath()).concat(FRAMEWORK_VIEW_SUFFIX);
			// ==4.执行跳转=========

			if (!res.isCommitted()) {
				if (v.getType() == View.TYPE.FORWARD)
					req.getRequestDispatcher(path).forward(req, res);
				else if (v.getType() == View.TYPE.REDIRECT) {
					res.sendRedirect(path);
				} else {
					throw new ServletException(
							"unknown response path exception:[" + v.getType().name() + "]:" + v.getPath());
				}
			}
		} catch (Exception e) {
			log.error("JSPResponseHandle", e);
		}
	}

}
